package com.txby.platformApi.component.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.jck.mybatis.util.PageList;
import com.jck.tools.ChkUtil;
import com.txby.platformCore.component.service.CommonController;
import com.txby.platformCore.data.CommonApiModelMapExt;
import com.txby.platformCore.entity.DoctorAdvice;
import com.txby.platformCore.entity.SickDetailInfo;
import com.txby.platformCore.entity.TxbyBDApiConfig;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 医嘱信息crud类
* @author 作者 jacking
* @date  
 */
@SuppressWarnings("all")
@RestController
@Api(value="医嘱信息",description="医嘱信息-说明")
@RequestMapping("/doctorAdvice")
public class DoctorAdviceController extends CommonController{
	private static Logger log = Logger.getLogger(DoctorAdviceController.class);
	
	
	@ApiOperation(value = "查询医嘱日期列表", notes = "查询医嘱日期列表-说明")
	@GetMapping("/getShouldExecDate/{type}/{token}")
/*	@ApiImplicitParams({
		@ApiImplicitParam(paramType="query",dataType="number",name="type",value="请求端（ 0:web,1:android,2:iphone）",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="token",value="用户令牌",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="bedNO",value="患者床号",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="sickAreaNO",value="床位病区号",required=true),
	})
	@GlobalLogAnnotation(logType=2,discription="查询医嘱日期列表")*/
	public Map getShouldExecDate(@PathVariable("type") Integer type, @PathVariable("token") String token,
								@RequestParam(required=true,name="deviceSN") String deviceSN) {
		CommonApiModelMapExt mm = chekTokenCahceValid(token, type);
		try {
			if (!isTokenValid) {
				return mm;
			}
			if(token.startsWith("demo:")){
				deviceSN=demoDeviceSN;
			}
			
			SickDetailInfo sdi = getSickDetailInfo(deviceSN);
			String inHosNO = "";
			if(sdi !=null && !ChkUtil.isEmpty(inHosNO=sdi.getInHosNO())) {
				if(log.isDebugEnabled()) {
					log.debug("doctorAdvice/getDoctorAdviceInfo inHosNO:"+inHosNO);
				}
			} 
			Map paramMap = new HashMap(2);
			String searchSql = " and  isValid=1 and date_format(shouldExecTime, '%Y-%m-%d')<=date_format(now(), '%Y-%m-%d')";
			if (!ChkUtil.isEmpty(inHosNO)) {
				if (inHosNO.contains("%") || inHosNO.contains("_")) {
					inHosNO = inHosNO.trim().replace("%", "\\%").replace("_", "\\_");
					searchSql += " and inHosNO = #{pojo.inHosNO} escape '\\'";
					paramMap.put("inHosNO", inHosNO.trim());
				} else {
					inHosNO = inHosNO.trim();
					searchSql += " and inHosNO = #{pojo.inHosNO} ";
					paramMap.put("inHosNO", inHosNO.trim());
				}
			}
			
			searchSql += " order by daily desc ";//默认时间倒序
			PageList pl=new PageList<>();
			if(propertySourceConfig.getIsExecuteHisHttp()!=null&&propertySourceConfig.getIsExecuteHisHttp().equals("true")) {
				List<TxbyBDApiConfig> bdInfoList=this.getTxbyBDApiConfigInfo(TxbyBDApiConfig.class.getName());
				if(!ChkUtil.isEmptyAllObject(bdInfoList)){
					TxbyBDApiConfig bdInfo=bdInfoList.get(0);
				  String json=this.getHttpResponseContent(bdInfo.getApiBaseUrl()+bdInfo.getApiServletPath(), "get",paramMap);
				}
				
			}else{
				pl = this.mBaseDao.findBySqlForPageList("select  distinct date_format(shouldExecTime, '%Y-%m-%d') daily from  "+mBaseDao.tableName(DoctorAdvice.class)+" where 1=1  "+searchSql, Map.class, null, paramMap);
			}
			
			if(pl==null || pl.getResultList()==null || pl.getResultList().size()==0) {
				mm.put(CommonApiModelMapExt.ERRCODE, 4500);
				mm.put(CommonApiModelMapExt.ERRMSG, "查询成功");
				mm.put("data", pl.getResultList());
				return mm;
			}
			mm.put(CommonApiModelMapExt.ERRCODE, 0);
			mm.put(CommonApiModelMapExt.ERRMSG, "查询成功");
			mm.put("data", pl.getResultList());
			return mm;
			
		} catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 1);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统异常");
		}

		return mm;
	}
	
	@ApiOperation(value = "查询医嘱基本信息", notes = "查询医嘱基本信息-说明")
	@GetMapping("/getDoctorAdviceInfo/{type}/{token}")
	/*	@ApiImplicitParams({
		@ApiImplicitParam(paramType="query",dataType="number",name="type",value="请求端（ 0:web,1:android,2:iphone）",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="token",value="用户令牌",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="bedNO",value="患者床号",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="sickAreaNO",value="床位病区号",required=true),
	})
	@GlobalLogAnnotation(logType=2,discription="查询医嘱基本信息")*/
	public Map getDoctorAdviceInfo(@PathVariable("type") Integer type, @PathVariable("token") String token,
			@RequestParam(required=false,name="queryStr") String queryStr,
			@RequestParam(required=false,name="shouldExecTime") String shouldExecTime,
			@RequestParam(required=false,name="shouldExecFlag") String shouldExecFlag,
			@RequestParam(required=true,name="deviceSN") String deviceSN,
			@RequestParam(required=false,name="cardType") String cardType) {
		CommonApiModelMapExt mm = chekTokenCahceValid(token, type);
		try {
			if (!true) {
				return mm;
			}
			SickDetailInfo sdi = getSickDetailInfo(deviceSN);
			String inHosNO = "";
			if(sdi !=null && !ChkUtil.isEmpty(inHosNO=sdi.getInHosNO())) {
				if(log.isDebugEnabled()) {
					log.debug("doctorAdvice/getDoctorAdviceInfo inHosNO:"+inHosNO);
				}
			} 
			Map paramMap = new HashMap<>();
			String searchSql = " and  isValid=1 ";
			if (!ChkUtil.isEmpty(inHosNO)) {
				if (inHosNO.contains("%") || inHosNO.contains("_")) {
					inHosNO = inHosNO.trim().replace("%", "\\%").replace("_", "\\_");
					searchSql += " and inHosNO = #{pojo.inHosNO} escape '\\'";
					paramMap.put("inHosNO", inHosNO.trim());
				} else {
					inHosNO = inHosNO.trim();
					searchSql += " and inHosNO = #{pojo.inHosNO} ";
					paramMap.put("inHosNO", inHosNO.trim());
				}
			}
			
			if (!ChkUtil.isEmpty(cardType)) {
				if (cardType.contains("%") || inHosNO.contains("_")) {
					cardType = cardType.trim().replace("%", "\\%").replace("_", "\\_");
					searchSql += " and cardType = #{pojo.cardType} escape '\\'";
					paramMap.put("cardType", cardType.trim());
				} else {
					cardType = cardType.trim();
					searchSql += " and cardType = #{pojo.cardType} ";
					paramMap.put("cardType", cardType.trim());
				}
			}
			
			if (!ChkUtil.isEmpty(queryStr)) {
				if (queryStr.contains("%") || queryStr.contains("_")) {
					queryStr = queryStr.trim().replace("%", "\\%").replace("_", "\\_");
					searchSql += " and (orderContent like '%"+queryStr+"%'  or shouldExecDetail like '%"+queryStr+"%' )";
					paramMap.put("queryStr", queryStr.trim());
				} else {
					queryStr = queryStr.trim();
					paramMap.put("queryStr", queryStr);
					searchSql += " and (orderContent like '%"+queryStr+"%' or shouldExecDetail like '%"+queryStr+"%' ) ";
				}
			}
			
			if (!ChkUtil.isEmpty(shouldExecFlag)) {
				searchSql += " and shouldExecFlag ="+shouldExecFlag+" ";
			}
			// 日期为空,取当前日期前一天的日期为值
/*			if(ChkUtil.isEmpty(shouldExecTime)) {
				shouldExecTime=com.jck.tools.easyui.DateUtils.format(new Date(), com.jck.tools.easyui.DateUtils.YYYYMMDD_10);
			}*/
			if (!ChkUtil.isEmpty(shouldExecTime)) {
				searchSql += " and date_format(shouldExecTime,'%Y-%m-%d')  ='"+shouldExecTime+"'   ";
			} else {
				searchSql += " and date_format(shouldExecTime,'%Y-%m-%d')  = date_format(now(), '%Y-%m-%d') ";
			}
			
			searchSql += " order by shouldExecTime desc"; // 时间倒序排列
			PageList pl=new PageList<>();
			if(propertySourceConfig.getIsExecuteHisHttp()!=null&&propertySourceConfig.getIsExecuteHisHttp().equals("true")){
				List<TxbyBDApiConfig> bdInfoList=this.getTxbyBDApiConfigInfo(TxbyBDApiConfig.class.getName());
				if(!ChkUtil.isEmptyAllObject(bdInfoList)){
					TxbyBDApiConfig bdInfo=bdInfoList.get(0);
					String json=this.getHttpResponseContent(bdInfo.getApiBaseUrl()+bdInfo.getApiServletPath(), "get",paramMap);
				}
				
			}else{
				pl = this.mBaseDao.findBySqlForPageList("select *, date_format(shouldExecTime, '%Y-%m-%d') daily from  "+mBaseDao.tableName(DoctorAdvice.class)+" where 1=1  "+searchSql, Map.class, null, paramMap);
			}
			if(pl==null || pl.getResultList()==null || pl.getResultList().size()==0) {
				mm.put(CommonApiModelMapExt.ERRCODE, 4500);
				mm.put(CommonApiModelMapExt.ERRMSG, "查询成功");
				mm.put("data", pl.getResultList());
				return mm;
			}
			// 结果集
//			List ret = new ArrayList();
			List plist = getParentIds(pl.getResultList());
			Set set=getTreeSet(plist);
			
			Map m = new HashMap();
			List ll = new ArrayList();
			for(Object s:set) {
				m = new HashMap();
				String ss = (String)s;
//				m.put("day", ss);
//				ll = new ArrayList();
				if(plist!=null && plist.size()>0) {
					Map pd;
					// 循环处理医嘱
					int size;
					for (int i=0;i<(size=plist.size());i++) {
						Map pd1=(Map) plist.get(i);
						List li = getChildById(pd1.get("cId")+"");
						if(li!=null && li.size()>0) {
							pd1.put("list", li);
						}
						String beginTime = (String) pd1.get("beginTime");
						if(beginTime.equals((String)s)) {
							ll.add(pd1);
						}
					}
				}
				m.put("list", ll);
//				ret.add(m);
				
			}	
			mm.put(CommonApiModelMapExt.ERRCODE, 0);
			mm.put(CommonApiModelMapExt.ERRMSG, "查询成功");
			List cardTypeList = new ArrayList();
			Map cardTypeMap1 = new HashMap();
			cardTypeMap1.put("cardType","1");
			cardTypeMap1.put("name","口服卡");
			
			Map cardTypeMap2 = new HashMap();
			cardTypeMap2.put("cardType","2");
			cardTypeMap2.put("name","注射卡");
			Map cardTypeMap3 = new HashMap();
			cardTypeMap3.put("cardType","3");
			cardTypeMap3.put("name","静滴卡");
			Map cardTypeMap4 = new HashMap();
			cardTypeMap4.put("cardType","4");
			cardTypeMap4.put("name","静推卡");
			cardTypeList.add(cardTypeMap1);
			cardTypeList.add(cardTypeMap2);
			cardTypeList.add(cardTypeMap3);
			cardTypeList.add(cardTypeMap4);
			mm.put("cardTypeList", cardTypeList);
			mm.put("data", ll);
			return mm;
		} catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 1);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统异常");
		}
		
		return mm;
	}

	


	@ApiOperation(value = "护士执行医嘱", notes = "护士执行医嘱-说明")
	@PostMapping("/updateDoctorAdvice/{type}/{token}")
/*	@ApiImplicitParams({
		@ApiImplicitParam(paramType="query",dataType="number",name="type",value="请求端（ 0:web,1:android,2:iphone）",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="token",value="用户令牌",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="bedNO",value="患者床号",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="sickAreaNO",value="床位病区号",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="inHosNO",value="住院号",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="isHide",value="是否匿名",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="checkRecord",value="查房记录",required=true)
	})
	@GlobalLogAnnotation(logType=2,discription="护士执行医嘱")*/
	public Map updateDoctorAdvice(@PathVariable("type") Integer type, @PathVariable("token") String token, String ids,
			@RequestParam(required=false,name="name") String name,@RequestParam(required=false,name="jobNo") String jobNo) {
		CommonApiModelMapExt mm = chekTokenCahceValid(token, type);
		try {
			if (!isTokenValid) {
				return mm;
			}
			// 去除非字母、数字和中文的字符
			name = name.replaceAll("[^(a-zA-Z0-9\\u4e00-\\u9fa5)]", "");
			JSONArray o=(JSONArray) JSONArray.parse(ids);
			Object[] idsArr = o.toArray();
//			SickDetailInfo sdi = getSickDetailInfo(deviceSN); 
			if (ids != null) {
				String sql = "update t_txby_doctorAdvice set shouldExecFlag=1, orderExeNurse='"+name+"' where cId in (";
				for(int i=0; i<idsArr.length;i++) {
					sql += idsArr[i];
					if(i<idsArr.length-1) {
						sql+=",";
					}
				}
				sql+=") or parentId in(";
				for(int i=0; i<idsArr.length;i++) {
					sql += idsArr[i];
					if(i<idsArr.length-1) {
						sql+=",";
					}
				}
				sql+=" ) and date_format(shouldExecTime,'%Y-%m-%d')  = date_format(now(), '%Y-%m-%d') and shouldExecFlag=0 ";
				SqlSessionTemplate sst = mBaseDao.getSqlSessionTemplate();
				this.mBaseDao.executeSql(sql,null);
				mm.put(CommonApiModelMapExt.ERRCODE, 0);
				mm.put(CommonApiModelMapExt.ERRMSG, "执行成功");
				return mm;
			} else {
				mm.put(CommonApiModelMapExt.ERRCODE, 0);
				mm.put(CommonApiModelMapExt.ERRMSG, "执行成功");
				return mm;
			} 
		} catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 1);
			mm.put(CommonApiModelMapExt.ERRMSG, "执行失败");
		}
		return mm;
	}
	
	
	private List getChildById(String pid) {
		String sql="SELECT cId,parentId,orderContent,orderType,orderMakeTime,orderMakeDoctor,shouldExecDetail,orderFlag,orderExeNurse,cardType,"
				  + "shouldExecTime,date_format(shouldExecTime, '%Y-%m-%d %H:%i') beginTime,date_format(shouldExecTime, '%H:%i') hourTime,"
				  + "shouldExecFlag,isLeaf FROM "+this.mBaseDao.tableName(DoctorAdvice.class)+" WHERE 1=1 ";
		if(!ChkUtil.isEmpty(pid)) {
			sql+=" and parentId="+pid+"";
		}
		List ad= this.mBaseDao.findBySql(sql, Map.class, null);
		return ad;
	}
	
	private Map getDoctorAdviceById(String id) {
		String sql="SELECT cId,parentId,orderContent,orderType,orderMakeTime,orderMakeDoctor,shouldExecDetail,orderFlag,orderExeNurse,cardType,"
				+ "shouldExecTime,date_format(shouldExecTime, '%Y-%m-%d %H:%i') beginTime,date_format(shouldExecTime, '%H:%i') hourTime,"
				+ "shouldExecFlag,isLeaf FROM "+this.mBaseDao.tableName(DoctorAdvice.class)+" WHERE 1=1 ";
		if(!ChkUtil.isEmpty(id)){
			sql+=" and cId="+id+"";
		}
		Map ad=(Map) this.mBaseDao.findBySqlUniqueObject(sql, Map.class, null);
		return ad;
	}
	

	private List getParentIds(List list) {
		Set<String> set = new HashSet<String>();
		if(list != null && list.size()>0) {
			for(Object o: list) {
				Map m=(Map)o;
				String parentId=(String) m.get("parentId");
				if("-1".equals(parentId)) {
					set.add((String) m.get("cId"));
				} else {
					set.add(parentId);
				}
			}
		}
		Map m = null;
		List<Map> li = new ArrayList<Map>();
		for(String s:set) {
			m=getDoctorAdviceById(s);
			li.add(m);
		}
		return li;
	}
	
	private Set getTreeSet(List list) {
		Set s = new TreeSet();
		if(list != null && list.size()>0) {
			for(Object o: list) {
				Map m=(Map)o;
				Date shouldExecTime=(Date) m.get("shouldExecTime");
				String date = com.jck.tools.easyui.DateUtils.format(shouldExecTime, com.jck.tools.easyui.DateUtils.YYYYMMDDHHMM_16);
				s.add(date);
			}
		}
		return s;
	}
	
}